package com.obrock;

import android.content.Context;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;

import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

/**
 * Created with IntelliJ IDEA.
 * User: Дмитрий Г. Кузнецов
 * Date: 15.10.12
 * Time: 16:33
 * To change this template use File | Settings | File Templates.
 */
public class ViewPrognosis extends LinearLayout {
    int bgColor;
    Context context;

    public Calendar[] viewPeriod;
    public double balance = 0.0;
    public double balanceDebt = 0.0;
    public double balanceCredit = 0.0;

    public Balance[] transfers = null;
    public Balance selectedTransfer = null;

    public ViewPrognosis(Calendar[] period, Context context) {
        super(context);
        this.context = context;
        this.viewPeriod = period;
        this.bgColor = context.getResources().getColor(R.color.background_color);
        refresh();
    }

    public ViewPrognosis(Calendar[] period, Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        this.viewPeriod = period;
        this.bgColor = context.getResources().getColor(R.color.background_color);
        refresh();
    }

    /*
    public ViewTransfers(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }
    */

    public Balance refresh() {
        inflate(context, R.layout.prognosis, this);
        //setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
        setBackgroundColor(bgColor);

        TableLayout container = (TableLayout) findViewById(R.id.container_prognosis);
        container.setColumnShrinkable(1, true);
        container.setColumnStretchable(1, true);
        container.removeAllViews();

        /*
        TextView accountTitle = (TextView) findViewById(R.id.account_title);
        TextView accountBalance = (TextView) findViewById(R.id.account_amount);
        TextView accountDetails = (TextView) findViewById(R.id.account_debt);
        ImageView accountIcon = (ImageView) findViewById(R.id.icon);

        LinearLayout blockLines = (LinearLayout) findViewById(R.id.block_lines);
        LinearLayout blockColumns = (LinearLayout) findViewById(R.id.block_columns);
        */


        transfers = Main.db.getPrognosis(viewPeriod);

        if (selectedTransfer == null && transfers.length > 0) {
            selectedTransfer = transfers[0];
        }


        int id = -1;
        View current = null;

        TableRow xrow = null;

        balance = 0.0;
        balanceDebt = 0.0;
        balanceCredit = 0.0;


        for (int i = 0; i < transfers.length; ++i) {
            Balance transfer = transfers[i];
            //boolean approved = new Balance(selectedTransfer.parentID).approved(viewPeriod);

            double transferAmount = 0.0;
            String subTitle = "";

            ImageView icon = new ImageView(context);
            icon.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
            icon.setAdjustViewBounds(true);
            icon.setMaxHeight(32);
            icon.setMaxWidth(32);
            icon.setPadding(0, 4, 0, 0);

            LinearLayout iconHolder = new LinearLayout(context);
            iconHolder.addView(icon);
            LayoutParams param = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
            iconHolder.setLayoutParams(param);

            transferAmount = transfer.amount;

            balance += transfer.amount;
            if (transfer.approved) {
                balanceDebt += transfer.amount;
            } else {
                balanceCredit += transfer.amount;
            }

            if (transfer.approved) {
                icon.setImageDrawable(getResources().getDrawable(R.drawable.tick));
            } else if (transfer.date.before(new Date())) {
                icon.setImageDrawable(getResources().getDrawable(R.drawable.warning));
            } else if ((transfer.flags & 0xFF) == Balance.FLAG_PERIOD_CREDIT
                    && transfer.accountTo != null && transfer.accountTo.type == Account.TYPE_DEBT) {
                icon.setImageDrawable(getResources().getDrawable(R.drawable.credit));
            } else if ((transfer.flags & 0xFF) == Balance.FLAG_PERIOD_CREDIT
                    && transfer.accountTo != null && transfer.accountTo.type == Account.TYPE_CARD) {
                icon.setImageDrawable(getResources().getDrawable(R.drawable.card));
            } else {
                icon.setImageDrawable(getResources().getDrawable(R.drawable.calendar));
            }
            subTitle = "";
            if (transfer.accountFrom != null) {
                subTitle += transfer.accountFrom.name;
            } else {
                subTitle += getResources().getString(R.string.transfer_empty);
            }

            if (subTitle.length() > 0) {
                subTitle += " → ";
                // ►
            }

            if (transfer.type == Balance.TYPE_COMPLEX) {
                String s = "";
                for (Complex c : transfer.complex) {
                    if (s.length() > 0) s += ", ";
                    if (c.account != null) {
                        s += c.account.name;
                    } else {
                        s += getResources().getString(R.string.transfer_empty);
                    }
                }
                subTitle += s;
            } else if (transfer.accountTo != null) {
                subTitle += transfer.accountTo.name;
            } else {
                subTitle += getResources().getString(R.string.transfer_empty);
            }


            LinearLayout column2 = new LinearLayout(context);
            column2.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
            column2.setOrientation(LinearLayout.VERTICAL);

            TextView name = Main.getTextView(context, transfer.name);
            name.setTypeface(Typeface.DEFAULT, Typeface.BOLD);
            name.setTextSize(16);
            correctColor(transfer, name);


            LinearLayout subrow = new LinearLayout(context);
            subrow.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
            subrow.setOrientation(LinearLayout.HORIZONTAL);

            TextView date = Main.getTextView(context, Main.datetimeString(transfer.date));
            date.setTextSize(12);
            date.setTypeface(Typeface.DEFAULT, Typeface.BOLD);
            date.setTextColor(getResources().getColor(R.color.total_color));
            correctColor(transfer, date);

            TextView sub = Main.getTextView(context, subTitle);
            sub.setTextSize(12);
            sub.setPadding(8, 0, 0, 0);
            correctColor(transfer, sub);


            subrow.addView(date);
            subrow.addView(sub);

            column2.addView(name);
            column2.addView(subrow);

            String anal = "";
            for (Analytics a : transfer.analytics.keySet()) {
                if (transfer.analytics.get(a) != null) {
                    if (anal.length() > 0) anal += ", ";
                    anal += transfer.analytics.get(a).name;
                }
            }

            if (anal.length() > 0) {
                TextView vanal = Main.getTextView(context, anal);
                vanal.setTextSize(12);
                vanal.setTextColor(getResources().getColor(R.color.list_color));
                correctColor(transfer, vanal);
                column2.addView(vanal);
            }

            LinearLayout column3 = new LinearLayout(context);
            column3.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
            column3.setOrientation(LinearLayout.VERTICAL);

            TextView amount = Main.getTextView(context, String.format("%.2f", transferAmount));
            amount.setGravity(Gravity.RIGHT);
            amount.setTypeface(Typeface.DEFAULT, Typeface.BOLD);
            amount.setTextSize(16);
            correctColor(transfer, amount);
            column3.addView(amount);

            xrow = Main.addRow(context, bgColor, i, new View[]{
                    iconHolder,
                    column2,
                    column3
            });

            xrow.setTag(Main.tagPrognosis);

            xrow.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View view, MotionEvent motionEvent) {
                    int id = view.getId();
                    selectedTransfer = transfers[id];
                    Main.setObject(Main.VIEW_PROGNOSIS, selectedTransfer);
                    Main.refreshCursor((ViewGroup) view.getParent(), id, bgColor);
                    return false;
                }
            });

            xrow.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {

                    ViewGroup v = (ViewGroup) view.getParent();
                    int id = view.getId();

                    selectedTransfer = transfers[view.getId()];
                    Main.doAction(Main.VIEW_PROGNOSIS, selectedTransfer);
                }
            });

            Main.context.registerForContextMenu(xrow);
            container.addView(xrow);

            if (selectedTransfer != null && transfers[i].balanceID == selectedTransfer.balanceID) {
                id = i;
                if (current != null) {
                    current = xrow;
                }
            }

        }


        if (id != -1) {
            Main.refreshCursor(container, id, bgColor);
            ((ScrollView) findViewById(R.id.scroll_prognosis)).post(
                    new ScrollTo(((ScrollView) findViewById(R.id.scroll_prognosis)), current));
        }

        //Main.refreshHeader();
        return selectedTransfer;

        /*
        accountIcon.setImageDrawable(getResources().getDrawable(R.drawable.calendar));
        accountTitle.setText(
                String.format("%tb %tY: %s",
                        viewPeriod[0],
                        viewPeriod[0],
                        getResources().getString(R.string.menu_prognosis)));
        accountBalance.setText(getResources().getString(R.string.prompt_payment_total, balance));
        accountDetails.setText(getResources().getString(R.string.prompt_payment_payed, balanceDebt));
        */

    }

    void correctColor(Balance transfer, TextView view) {
        Calendar c = Calendar.getInstance(TimeZone.getDefault());
        c.setTime(transfer.date);
        if (transfer.approved) {
            view.setTextColor(getResources().getColor(R.color.approved));
        } else if (transfer.date.getTime() < new Date().getTime() ||
                transfer.date.getTime() < viewPeriod[0].getTimeInMillis()) {
            view.setTextColor(getResources().getColor(R.color.alert));
        } else if (viewPeriod[0].get(Calendar.MONTH) != c.get(Calendar.MONTH)) {
            view.setTextColor(getResources().getColor(R.color.future));
        }
    }


}
